package com.esun.cheetah.view.news;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.news.NewsHeadCommunicater;
import com.esun.cheetah.biz.personal.personalinfo.UserInfo;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.model.news.NewsHeadBean;
import com.esun.cheetah.network.ConnectionChangeReceiver;
import com.esun.cheetah.view.personal.lotteryinfoact.PullToRefreshListViewNews;
import com.esun.util.log.EDebug;

public class LotteryNewsAct extends Activity implements OnScrollListener, OnItemClickListener, PullToRefreshListViewNews.OnRefreshListener,
		OnClickListener, PullToRefreshListViewNews.OnPrepareForRefreshListener {
	private PullToRefreshListViewNews listViewNewsTotal; // 全部新闻记录列表
	private ArrayList<Hashtable<String, String>> alItem; // 列表数据存储
	private ArrayList<View> itemViewList;
	private NewsAdapter adapter;
	private LinearLayout linearFooter; // 列表底部加载布局
	private LinearLayout linearNoMore;
	private LinearLayout linearBottom;

	// private RelativeLayout rl;

	private RelativeLayout newsMainLayout;

	private Button news_agp_btn_refresh;
	// private LinearLayout news_agp_ll_refresh;

	private ProgressDialog progressDialog;
	public static Handler handlerNews;
	private NewsHeadCommunicater newsHeadCommunicater;
	// private String serverMessage; // 服务器返回信息
	private int refreshORBottom = 2; // state=1刷新 state=2到底部
	// private Intent intent;
	// private Bundle bundle;
	private LinearLayout linearNoMoreNews;
	private boolean isShow = true;
	private boolean isRunning;// 是否正在通信
	private boolean isFirstLoad = true; // 是否是第一次加载
	private boolean isNoMoreRecord = true; // 是否还有记录
	private boolean isBottomChanged = false;

	private int PAGENO = 1;
	private String COLID = "10";

	private final int NEWS_VIEW_TAG = 10000;
	private final int NEWS_VIEW_TAG2 = 20000;
	private final int NEWS_VIEW_TAG3 = 30000;

	/** add 调整无记录时提示语 */
	private TextView tvNoNews;
	// private ProgressBar pbRef;
	private Button btnRef;
	private String strNoNews = "暂无近期新闻";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_total_act);

		initHandler();
		initUI();

	}

	@Override
	protected void onPause() {

		// TODO Auto-generated method stub
		super.onPause();
		isShow = false;
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {

		// TODO Auto-generated method stub
		super.onResume();
		isShow = true;
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
		if (UserInfo.getUserInfo().isRebuy()) {
			getParent().finish();
		}
	}

	// 初始化
	public void initUI() {

		isRunning = false;

		// progressDialog = ViewerUtil.showProgressDialog(LotteryNewsAct.this,
		// getResources().getString(R.string.loading_text));
		// progressDialog.show();
		listViewNewsTotal = (PullToRefreshListViewNews) findViewById(R.id.newstotalact_listview);
		newsMainLayout = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.news, null);
		linearFooter = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryinfoact_linear_footer, null);
		linearNoMore = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryrecordlist_act_linear_nomore, null);
		linearBottom = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.listview_bottom_view, null);
		linearFooter.setTag(NEWS_VIEW_TAG);
		linearNoMore.setTag(NEWS_VIEW_TAG2);
		linearBottom.setTag(NEWS_VIEW_TAG3);

		alItem = new ArrayList<Hashtable<String, String>>();
		itemViewList = new ArrayList<View>();
		adapter = new NewsAdapter(LotteryNewsAct.this, alItem, itemViewList);
		listViewNewsTotal.addFooterView(linearFooter);// 增加底部状态条
		listViewNewsTotal.setAdapter(adapter);
		listViewNewsTotal.removeFooterView(linearFooter);
		linearNoMoreNews = (LinearLayout) findViewById(R.id.news_total_linear_noRecord);

		// 手动更改list背景颜色
		// rl = (RelativeLayout) findViewById(R.id.news_rl);
		// rl.setBackgroundColor(R.color.BgColor);

		listViewNewsTotal.setOnItemClickListener(this);
		listViewNewsTotal.setOnRefreshListener(this);
		listViewNewsTotal.setOnScrollListener(this);
		listViewNewsTotal.setOnPrepareForRefreshListener(this);

		tvNoNews = (TextView) findViewById(R.id.news_total_tv_norecord);
		tvNoNews.setText(strNoNews);
		// pbRef = (ProgressBar) newsMainLayout
		// .findViewById(R.id.news_agp_pb_refresh);
		btnRef = (Button) newsMainLayout.findViewById(R.id.news_agp_btn_refresh);
		btnRef.setOnClickListener(this);

		news_agp_btn_refresh = (Button) getParent().findViewById(R.id.news_agp_btn_refresh);
		// news_agp_ll_refresh = (LinearLayout)
		// getParent().findViewById(R.id.news_agp_ll_refresh);

		news_agp_btn_refresh.setVisibility(View.VISIBLE);
		// news_agp_ll_refresh.setVisibility(View.VISIBLE);

	}

	// 与服务器通信线程
	public void getNewsThread() {
		newsHeadCommunicater = new NewsHeadCommunicater(handlerNews, COLID, PAGENO);
		newsHeadCommunicater.startCommunicate();

	}

	// 消息处理
	public void initHandler() {
		handlerNews = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				listViewNewsTotal.removeFooterView(linearBottom);

				switch (msg.what) {
				case Config.COMMUNICATER_SUCCESS:

					if (newsHeadCommunicater.getLotteryList().size() == 0) {
						isNoMoreRecord = false;
						if (PAGENO == 0) {
							linearNoMoreNews.setVisibility(View.VISIBLE);
						} else {
							listViewNewsTotal.addFooterView(linearNoMore);
						}
					} else {
						PAGENO++;

						communicateSucceed(newsHeadCommunicater.getLotteryList());

						itemViewList.clear();
						adapter.notifyDataSetChanged();
						if (newsHeadCommunicater.getLotteryList().size() < 10) {
							isNoMoreRecord = false;
							listViewNewsTotal.addFooterView(linearNoMore);
						}
					}

					lengthAutoAdapter();
					endProcess();
					break;

				case Config.COMMUNICATER_FAIL:

					// 通讯失败
					if (isShow) {
						// ViewerUtil.showTipDialog(LotteryNewsAct.this,
						// newsHeadCommunicater.getServerMsg(), false);
						Toast.makeText(LotteryNewsAct.this, newsHeadCommunicater.getServerMsg().toString(), 0).show();
					}
					lengthAutoAdapter();
					endProcess();

					break;
				case Config.COMMUNICATER_EXCEPTION:

					if (isShow) {
						// ViewerUtil.showTipDialog(LotteryRecordUndoneAct.this,
						// Language.BUG_DIALOG_WEIJIE, false);
						// listViewLotteryRecordTotal.addFooterView(linearNoMore);

						// Toast.makeText(LotteryNewsAct.this,
						// Language.NEWS_TOAST_NEWS.toString(),
						// 0).show();
						linearNoMoreNews.setVisibility(View.VISIBLE);
					}
					lengthAutoAdapter();
					endProcess();

					break;

				case Config.DO_REFRESH:
					EDebug.o(this, "do refresh");
					if (!isRunning) {
						if (alItem.size() > 5) {
							for (int i = 0; i < alItem.size(); i++) {
								if (i >= (alItem.size() - 5) & i < alItem.size())
									alItem.remove(i);
							}
						}
						adapter.notifyDataSetChanged();
						listViewNewsTotal.prepareForRefresh();
						listViewNewsTotal.onRefresh();
						// progressDialog.show();
						// pbRef.setVisibility(View.VISIBLE);
					}
					NewsAct.isCanClick = true;

					break;

				default:
					break;
				}
			}
		};
	}

	private void endProcess() {

		news_agp_btn_refresh.setVisibility(View.VISIBLE);
		// news_agp_ll_refresh.setVisibility(View.GONE);
		progressDialog = Constant.bar;

		if (refreshORBottom == 1) {
			listViewNewsTotal.onRefreshComplete();
		} else {
			listViewNewsTotal.removeFooterView(linearFooter);
		}
		if (progressDialog != null) {
			progressDialog.cancel();

			// pbRef.setVisibility(View.GONE);

		}
		isRunning = false;
	}

	// 通讯成功处理
	public void communicateSucceed(ArrayList<NewsHeadBean> LotteryNews) {

		ArrayList<Hashtable<String, String>> alItemTemp = new ArrayList<Hashtable<String, String>>();

		for (int i = 0; i < LotteryNews.size(); i++) {

			Hashtable<String, String> map = new Hashtable<String, String>();
			// 显示参数
			map.put("bigtitle", LotteryNews.get(i).bigtitle);
			map.put("id", LotteryNews.get(i).id);

			alItemTemp.add(map);
			childCount++;
		}
		if (refreshORBottom == 1) {
			alItem.clear();
		}
		alItem.addAll(alItemTemp);
	}

	// 到底事件
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if ((firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0)) {
			if (isNoMoreRecord) {
				System.out.println("onScroll");
				if (isFirstLoad) {
					listViewNewsTotal.prepareForRefresh();
					listViewNewsTotal.onRefresh();
					isFirstLoad = false;
				} else {
					if (!isRunning && isBottomChanged) {
						isRunning = true;
						isBottomChanged = false;
						listViewNewsTotal.addFooterView(linearFooter);
						refreshORBottom = 2;
						getNewsThread();
					}
				}
			}
		} else {
			isBottomChanged = true;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	// 将menu键点击事件返回给父activity处理
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		if (!isRunning) {
			System.out.println("onRefresh");
			news_agp_btn_refresh.setVisibility(View.VISIBLE);
			// news_agp_ll_refresh.setVisibility(View.VISIBLE);
			PAGENO = 1;
			isRunning = true;
			isNoMoreRecord = true;
			refreshORBottom = 1;
			groupCount = 0;
			childCount = 0;
			itemViewList.clear();
			linearNoMoreNews.setVisibility(View.GONE);
			if (listViewNewsTotal.getFooterViewsCount() != 0) {
				listViewNewsTotal.removeFooterView(linearNoMore);
			}
			getNewsThread();
		}
	}

	@Override
	public void onPrepareForRefresh() {
		news_agp_btn_refresh.setVisibility(View.VISIBLE);
		// news_agp_ll_refresh.setVisibility(View.VISIBLE);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		adapter.notifyDataSetChanged();
		if (arg1.getTag() != null
				&& (Integer.parseInt(String.valueOf(arg1.getTag())) == NEWS_VIEW_TAG
						|| Integer.parseInt(String.valueOf(arg1.getTag())) == NEWS_VIEW_TAG2 || Integer.parseInt(String.valueOf(arg1
						.getTag())) == NEWS_VIEW_TAG3)) {
			return;
		} else {
			startActivity(new Intent(LotteryNewsAct.this, NewsContent.class).putExtra("url", Config.NEWS_CONTENT
					+ alItem.get(arg2 - 1).get("id")));
		}

		// 修改字体颜色
		TextView textView = (TextView) arg1.findViewById(R.id.news_table_new_tv_newshead);
		if (textView != null) {
			textView.setTextColor(Color.GRAY);
			RecordTV.put(arg2, Color.GRAY);
		}
		ImageView imageView = (ImageView) arg1.findViewById(R.id.news_table_new_imageview_arrows);
		if (imageView != null) {
			imageView.setBackgroundResource(R.drawable.img_pressed_dot);
			RecordIM.put(arg2, R.drawable.img_pressed_dot);
		}

	}

	@Override
	public void onClick(View v) {
		// progressDialog = Constant.bar;
		Message msg = new Message();
		msg.what = Config.DO_REFRESH;

		switch (v.getId()) {
		case R.id.news_agp_btn_refresh:
			LotteryNewsAct.handlerNews.sendMessage(msg);
			getNewsThread();

			EDebug.o("刷新按钮--->启动");
			//
			// listViewNewsTotal.prepareForRefresh();
			// listViewNewsTotal.onRefresh();
			// progressDialog.show();
			break;

		default:

			break;

		}
	}

	Map<Integer, Integer> RecordTV = new HashMap<Integer, Integer>();// 点击后记录字体颜色
	Map<Integer, Integer> RecordIM = new HashMap<Integer, Integer>();// 点击后记录图片

	public class NewsAdapter extends BaseAdapter {
		private LayoutInflater listInflater;

		private ArrayList<Hashtable<String, String>> list = new ArrayList<Hashtable<String, String>>();

		private TextView tvNews;
		private ImageView imNews;
		// private ImageView imNewsArrow;
		private static final String NEWSHEAD = "bigtitle";

		// private static final String NEWSTIME = "time";

		public NewsAdapter(Context context, ArrayList<Hashtable<String, String>> tempList, ArrayList<View> tempViewList) {
			this.listInflater = LayoutInflater.from(context);
			this.list = tempList;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			// return recordListView.get(position);
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			convertView = listInflater.inflate(R.layout.news_listtable, null);
			tvNews = (TextView) convertView.findViewById(R.id.news_table_new_tv_newshead);

			imNews = (ImageView) convertView.findViewById(R.id.news_table_new_imageview_arrows);

			// imNewsArrow = (ImageView) convertView
			// .findViewById(R.id.news_table_new_imageview_arrow);

			tvNews.setText(list.get(position).get(NEWSHEAD));

			EDebug.o(NewsAdapter.this, "新闻头标签" + list.get(position).get(NEWSHEAD));

			// //如果无数据显示一个无数据的title并且去个箭头
			// if (list.get(position).get(NEWSTIME).equals("0")) {
			// imNewsArrow.setVisibility(View.GONE);
			// }

			tvNews.setTextColor(Color.BLACK);// 你默认的字体颜色
			if (RecordTV.containsKey(position + 1)) {
				tvNews.setTextColor(Color.GRAY);// 点击后的字体颜色
			}

			imNews.setBackgroundResource(R.drawable.img_default_dot);// 你默认的图片
			if (RecordIM.containsKey(position + 1)) {
				imNews.setBackgroundResource(R.drawable.img_pressed_dot);// 点击后的图片
			}
			return convertView;
		}

	}

	private int groupCount = 0;
	private int childCount = 0;

	private void lengthAutoAdapter() {
		int itemHeight = 30 * groupCount + childCount * (30 + 1);

		// 判断是否需要加入额外item
		if (itemHeight < listViewNewsTotal.getHeight()) {
			LinearLayout linearChild = new LinearLayout(this);
			int bheight = 0;
			// linearChild.setBackgroundColor(R.color.wxx);
			// Color.WHITE
			if (listViewNewsTotal.getFooterViewsCount() > 0) {
				bheight = listViewNewsTotal.getHeight() - itemHeight - 30;
			} else {
				bheight = listViewNewsTotal.getHeight() - itemHeight;
			}
			linearBottom.addView(linearChild);
			for (int i = 0; i < linearBottom.getChildCount(); i++) {
				linearBottom.getChildAt(i).getLayoutParams().height = bheight;
				linearBottom.getChildAt(i).getLayoutParams().width = LayoutParams.FILL_PARENT;
			}
			TextView a = new TextView(linearChild.getContext());
			a.setFocusable(true);
			a.setBackgroundResource(R.drawable.anull_icon);
			linearChild.addView(a);
			linearChild.setVisibility(View.VISIBLE);
			listViewNewsTotal.addFooterView(linearBottom);
		}
	}

}
